#!/usr/bin/python
# encoding=utf-8
import json
import sys
import apis.aep_device_status
import apis.aep_device_command
import apis.aep_device_management
import base64
import time
import use_database
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
appKey ='vKQUt3OMKAh'
appsecret ='uIGFrBQLG1'
MasterKey='eeb911a06b6a4d3fa1f0610c46e56918'
sys.path.append('..')
def crc16(x,invert=False):
    # 预置16位全1寄存器
    # python能够是被16进制格式的数，0x会被判定为16进制
    a = 0xFFFF
    b = 0xA001
    # ord:获取ASCII给定字符的值
    # a^-b:两数的二进制形式异或取值
    # %2:取二进制的最后一位
    for byte in x:
        last = a % 2
        # 把寄存器的内容右移1位，用填补最高位
        a >>= 1
        # 重复右移操作，如果移出位为1，则寄存器与A001异或
        if last == 1:
            a ^=b
    # upper()变为大写
    s = hex(a).upper()
    # 去掉8X，根据是否反转得到CRC16校验码
    return s[4:6] + s[2:4] if invert == True else s[2:4] + s[4:6]
class SMTPSender:
    def __init__(self, username, authorization_code):
        self.username = username
        self.authorization_code = authorization_code
        self.smtp_server = 'smtp.qq.com'
        self.smtp_port = 465

    def send_email(self, subject, content_text, recipients):
        try:
            msg = MIMEMultipart()
            msg['From'] = self.username
            msg['To'] = ', '.join(recipients)
            msg['Subject'] = subject
            msg.attach(MIMEText(content_text, 'plain'))

            # 创建SMTP连接
            with smtplib.SMTP_SSL(self.smtp_server, self.smtp_port) as server:
                server.login(self.username, self.authorization_code)
                server.sendmail(self.username, recipients, msg.as_string())

            print("Email sent successfully!")
        except Exception as e:
            print(f"Error: unable to send email. {str(e)}")

if __name__ == '__main__':
    last_received_time = time.time()  # 初始化接收时间
    last_time=''
    count=0
    while True:
        if count==3:
            # 使用示例
            username = "2072606225@qq.com"
            # 邮箱授权码
            authorization_code = "dwkggiqppdnebghf"

            # 实例化SMTPSender对象
            smtp_sender = SMTPSender(username, authorization_code)

            # 邮件主体内容
            subject = "deviceid：1528564111 出现问题，未收到信息"
            content_text = "deviceid：1528564111 出现问题，未收到信息"
            recipients = ["2072606225@qq.com"]  # 替换为实际收件人

            # 发送邮件
            smtp_sender.send_email(subject, content_text, recipients)
            count=0
        data_received = False  # 初始化标记是否收到数据
        deviceid = '1528564111'
        try:
            result = apis.aep_device_status.QueryDeviceStatusList('vKQUt3OMKAh', 'uIGFrBQLG1',
                                                                  '{"productId":"15285641",'
                                                                  '"deviceId":"%s", '
                                                                  '"datasetId":"APPdata"}' % deviceid)
        except:
            time.sleep(2)
            continue  # 如果查询失败，则重试
        try:
            result = json.loads(result)
            if result['code'] == 1:
                print('\t', result['desc'])
                continue
            if not result['deviceStatusList']:
                print('\tdeviceStatusList为空')
                continue
            timestamp = str(result['deviceStatusList'][0]['timestamp'])
            message = str(base64.b64decode(result['deviceStatusList'][0]['value']))
            message = message.replace('b\'', '').replace('\'', '')
        except:
            time.sleep(2)
            continue  # 如果处理数据失败，则重试
        try:
            message = message.replace('nan', '0')  # 处理NaN值
            message = json.loads(message)
            message['timestamp'] = timestamp

        except:
            print('\t接收数据为:', message)
            continue  # 如果处理JSON失败，则重试
        if last_time==message['timestamp']:
            print('\t未收到信息')
            time.sleep(10)
            count=count+1
            continue
        else:
            last_time=message['timestamp']
        if str(message.get('latitude')) == '0':
            print("经纬度无效")
            time.sleep(10)  # 每次循环等待10秒

            continue  # 如果纬度为0，不处理
        try:
            use_database.run_updates(message)  # 尝试更新数据库
            data_received = True  # 成功更新数据库，标记为接收到数据
            last_received_time = time.time()  # 更新接收时间
            print('\t接收数据为:', message)
        except Exception as e:
            print('\t数据库更新失败:', e)
            continue
        time.sleep(9)  # 每次循环等待10秒
        if not data_received and time.time() - last_received_time > 10:
            print('\t未收到信息')
            last_received_time = time.time()  # 重置接收时间
